package services

import (
	"encoding/json"
	"os"
	"time"

	"homepage-backend/internal/models"
)

// LoadLinks 从文件加载友链数据
func LoadLinks(filePath string) ([]models.Link, error) {
	file, err := os.ReadFile(filePath)
	if err != nil {
		return nil, err
	}
	var links []models.Link
	if err := json.Unmarshal(file, &links); err != nil {
		return nil, err
	}
	return links, nil
}

// AddLink 添加新友链（自动生成唯一ID和添加时间）
func AddLink(filePath string, link models.Link) error {
	if link.Name == "" || link.URL == "" {
		return nil // 名称和URL必填
	}
	links, err := LoadLinks(filePath)
	if err != nil && !os.IsNotExist(err) {
		return err
	}
	link.ID = GenerateShortID(link.Name + link.URL + time.Now().Format(time.RFC3339Nano))
	link.AddTime = time.Now().Unix()
	links = append(links, link)
	return saveLinks(filePath, links)
}

// UpdateLink 修改友链（按ID匹配）
func UpdateLink(filePath string, link models.Link) error {
	if link.ID == "" {
		return nil
	}
	links, err := LoadLinks(filePath)
	if err != nil {
		return err
	}
	for i, l := range links {
		if l.ID == link.ID {
			link.AddTime = l.AddTime // 保留原有添加时间
			links[i] = link
			return saveLinks(filePath, links)
		}
	}
	return nil // 未找到不报错
}

// DeleteLink 删除友链（按ID）
func DeleteLink(filePath string, id string) error {
	if id == "" {
		return nil
	}
	links, err := LoadLinks(filePath)
	if err != nil {
		return err
	}
	newLinks := make([]models.Link, 0, len(links))
	for _, l := range links {
		if l.ID != id {
			newLinks = append(newLinks, l)
		}
	}
	return saveLinks(filePath, newLinks)
}

// saveLinks 保存友链数据到文件
func saveLinks(filePath string, links []models.Link) error {
	data, err := json.MarshalIndent(links, "", "  ")
	if err != nil {
		return err
	}
	return os.WriteFile(filePath, data, 0644)
}
